package club.ruanx.movie.security.rbac;

import club.ruanx.constraint.RedisConstraint;
import club.ruanx.util.CollectionUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.Set;

/**
 * @author 阮胜
 * @date 2018/9/22 19:29
 */
@Component("rbacAuthenticateService")
public class RbacAuthenticateServiceImpl implements RbacAuthenticateService {
    private static final String ANONYMOUS_USER = "anonymousUser";
    private static final String SUPER_ADMIN = "ROLE_SUPERADMIN";
    private final RedisTemplate<String, Object> redisTemplate;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    public RbacAuthenticateServiceImpl(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        if (CollectionUtils.isEmpty(authorities)) {
            return false;
        } else {
            for (GrantedAuthority authority : authorities) {
                if (authority.getAuthority().equalsIgnoreCase(SUPER_ADMIN)) {
                    return true;
                }
            }
        }
        String username = authentication.getName();
        if (StringUtils.isEmpty(username) || username.equalsIgnoreCase(ANONYMOUS_USER)) {
            return false;
        }
        @SuppressWarnings("unchecked")
        Set<String> urlSet = (Set<String>) redisTemplate.opsForHash().get(RedisConstraint.SYS_USER_ACL_MAP_NAME, username);
        if (CollectionUtils.isEmpty(urlSet)) {
            return false;
        }
        boolean hasPermission = false;
        for (String url : urlSet) {
            if (antPathMatcher.match(url, request.getRequestURI())) {
                hasPermission = true;
                break;
            }
        }
        return hasPermission;
    }


}
